package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;


import com.alibaba.fastjson.JSON;
import com.cloudbroker.bcs.common.constants.type.BusinessType;
import com.cloudbroker.bcs.common.util.DecimalFormatUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.credits.api.vo.request.CreditsOperForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.baseRelevanted.AuthuserRegbindForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.RegForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.base.HeaderForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.CapitalAccountLoginForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.LoginForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.UserinfoForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.AuthuserRegbindVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.IFS.CapitalAccountLoginVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.IFS.LoginVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.IFS.RegisterVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.IFS.UserinfoVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.RegBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.UserStatus;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.UserType;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.VerifySource;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.BrokerVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.base.vo.UserVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.customer.CustomerBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.customer.back.CustomerBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.customer.vo.CustomerRegForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.RegisterForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.UserLoginBack;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.customer.vo.CapitalLoginForm;
import com.cloudbroker.bcs.platform.ltb.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.ltb.middle.entity.Customer;
import com.cloudbroker.bcs.platform.ltb.middle.entity.InviteLog;
import com.cloudbroker.bcs.platform.ltb.middle.entity.UserEntity;
import com.cloudbroker.bcs.platform.ltb.middle.entity.credits.CreditsLog;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.credits.CreditsExtService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.usercenter.UserCenterService;
import com.cloudbroker.bcs.platform.ltb.middle.model.UserCache;
import com.cloudbroker.bcs.platform.ltb.middle.service.*;
import com.cloudbroker.bcs.platform.ltb.middle.util.MD5Util;
import com.cloudbroker.bcs.platform.ltb.middle.util.UserTokenUtil;
import com.cloudbroker.bcs.platform.ltb.middle.util.VerifyCodeTokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;

import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.ClientErr.*;
import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.CommonErr.*;

/**
 * Created by tianrui on 2016/7/5.
 */

@Service
public class CustomerBizServiceImpl implements CustomerBizService {

    //跟投用户信息表操作
    @Resource
    private CustomerService customerService;

    //验证码存入缓存
    @Resource
    private ValidateCodeService validateCodeService;

    //用户登录表操作
    @Resource
    private UserService userService;

    //后台接口调用
    @Resource
    private LightinvestingService lightinvestingService;
    @Resource
    private PushService pushService;

    private Logger logger = Logger.getLogger(CustomerBizServiceImpl.class);

    @Resource
    private UserCenterService userCenterService;

    @Resource
    private InviteLogService inviteLogService;

    @Resource
    private CreditsLogService creditsLogService;
    @Resource
    private CreditsExtService creditsService;

    /**
     * 跟投用户注册
     * */
    @Override
    @Transactional
    public UserLoginBack funcCustomerRegister(CustomerRegForm form)  {
        String mobile_tel = form.getMobile_tel();
        String sendercomp_id = form.getSendercomp_id();
        String user_type = String.valueOf(UserType.CUSTOMER.getVal());
        String alias_name = mobile_tel;
        String company_id = form.getCompany_id();
        String verify_code = form.getAuth_check_code();
        if (ConfigValues.getVerifyCodeSuperSwitch()){
            if (!verify_code.equals(ConfigValues.getVerifyCodeSuperValue())){
                return VOUtil.genErrorResult(VERIFY_CODE_WRONG, UserLoginBack.class);
            }
        }
        else{
            String verify_token = VerifyCodeTokenUtil.getVerifyCodeToken(mobile_tel + company_id + sendercomp_id,
                    VerifySource.CUSTOMER_REGISTER);
            if (VerifyCodeTokenUtil.isTimeOut(verify_token)){
                return VOUtil.genErrorResult(HSBCPSErrorCodes.CommonErr.VERIFY_CODE_TIMEOUT, UserLoginBack.class);
            }
            if (!VerifyCodeTokenUtil.isRight(verify_token, verify_code)){
                return VOUtil.genErrorResult(VERIFY_CODE_WRONG, UserLoginBack.class);
            }
        }
        //邀请码
        UserEntity inviteUser=null;
        if(StringUtils.isNotBlank(form.getInvite_code())) {
            inviteUser = userService.findByInviteCode(new UserEntity(form.getInvite_code()));
            if(inviteUser==null){
                return VOUtil.genErrorResult(INVITE_CODE_NOT_EXIT, UserLoginBack.class);
            }
        }


        UserEntity isRegUser = userService.getUserEntity(new UserEntity(mobile_tel, user_type,
                sendercomp_id, form.getCompany_id()));
        if(null != isRegUser){
            return VOUtil.genErrorResult(MOBILE_REGISTERED, UserLoginBack.class);
        }

//        CheckRegisterForm checkRegisterForm = new CheckRegisterForm();
//        checkRegisterForm.setTenant_id(form.getCompany_id());
//        checkRegisterForm.setUser_type("3");
//        checkRegisterForm.setLogin_account(mobile_tel);
//        CheckRegisterVo checkRegisterVo = userCenterService.func_check_register(checkRegisterForm);
//        if(!"0".equals(checkRegisterVo.getIs_register())){
//            return VOUtil.genErrorResult(checkRegisterVo.getError_no(),checkRegisterVo.getError_info(), UserLoginBack.class);
//        }
        com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm userRegisterForm =
                new com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.ifs.RegisterForm();
        userRegisterForm.setLogin_account(mobile_tel);
        userRegisterForm.setAuth_password(MD5Util.encrypt(form.getPassword()));
        userRegisterForm.setUser_type("3");
        userRegisterForm.setTenant_id(form.getCompany_id());
        userRegisterForm.setAlias_name(mobile_tel);
        userRegisterForm.setRegister_flag("2");
        userRegisterForm.setMobile(mobile_tel);
        RegisterVo userT2RegBack = userCenterService.func_register(userRegisterForm);
        if(!"0".equals(userT2RegBack.getError_no())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genErrorResult(userT2RegBack.getError_no(),userT2RegBack.getError_info(), UserLoginBack.class);
//            throw new RuntimeException(userT2RegBack.getError_no() + "|" + userT2RegBack.getError_info());
        }

        Customer new_customer =new Customer(alias_name,mobile_tel,
                System.currentTimeMillis(), company_id);
        customerService.addCustomer(new_customer);

        //注册到ITN
        AuthuserRegbindForm authuserRegbindForm = new AuthuserRegbindForm();
        authuserRegbindForm.setBusinsys_no(Long.valueOf(1001));
        authuserRegbindForm.setSendercomp_id(form.getSendercomp_id());
        authuserRegbindForm.setMobile_tel(mobile_tel);
        authuserRegbindForm.setUser_token(form.getUser_token());
        AuthuserRegbindVo authuserRegbindVo = new AuthuserRegbindVo();
        try {
            authuserRegbindVo = lightinvestingService.func_services_authuser_regbind(authuserRegbindForm);
        }catch (Exception e){
            //成功与否不要影响注册流程
            e.printStackTrace();
        }
        if (authuserRegbindVo == null || authuserRegbindVo.getUser_id() == null){
            authuserRegbindVo.setUser_id("0");
        }
        //刷新user信息
        long customer_id = new_customer.getCustomer_id();
        //更新user表
        String user_key = String.valueOf(System.nanoTime());
        UserEntity userEntity = new UserEntity();
        userEntity.setUser_id(Long.parseLong(userT2RegBack.getUser_id()));
        userEntity.setAccounts_id(customer_id);
        userEntity.setCompany_id(form.getCompany_id());
        userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
        userEntity.setSendercomp_id(form.getSendercomp_id());
        userEntity.setUser_name(form.getMobile_tel());
        userEntity.setAlias_name(form.getMobile_tel());
        userEntity.setUser_status(String.valueOf(UserStatus.NORMAL.getVal()));
        userEntity.setMobile(form.getMobile_tel());
        userEntity.setInvite_code(DecimalFormatUtil.format(Long.parseLong(userT2RegBack.getUser_id()),"00000000"));
        userService.addUser(userEntity);
        //保存极光推送信息
        if(!StringUtil.isEmpty(form.getRegistration_id())) {
            RegisterForm regForm = new RegisterForm();
            regForm.setRegistration_id(form.getRegistration_id());
            UserVO userVO = new UserVO();
            userVO.setUser_id(userEntity.getUser_id());
            regForm.setUser(userVO);
            regForm.setCompany_id(form.getCompany_id());
            regForm.setSendercomp_id(form.getCompany_id());
            regForm.setTerminal_type(form.getTerminal_type());
            regForm.setAlias_name(String.valueOf(userEntity.getUser_id()));
            try{
                pushService.registrationIdMgr(regForm);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
//        userService.updateID(Long.parseLong(userT2RegBack.getUser_id()),userEntity.getUser_id());
        //用户中心登录
        LoginForm userT2LoginForm = new LoginForm();
        userT2LoginForm.setLogin_account(mobile_tel);
        userT2LoginForm.setAuth_password(MD5Util.encrypt(form.getPassword()));
        userT2LoginForm.setUser_type("3");
        userT2LoginForm.setTenant_id(form.getCompany_id());
        LoginVo userT2LoginBack = userCenterService.func_login(userT2LoginForm);
        if(!"0".equals(userT2LoginBack.getError_no())) {
            return VOUtil.genErrorResult(userT2LoginBack.getError_no(),userT2LoginBack.getError_info(),UserLoginBack.class);
        }
        UserinfoForm userinfoForm = new UserinfoForm();
        userinfoForm.setUser_token(userT2LoginBack.getUser_token());
        UserinfoVo userT2InfoBack = userCenterService.func_userinfo(userinfoForm);
        if(!"0".equals(userT2InfoBack.getError_no())) {
            return VOUtil.genErrorResult(userT2InfoBack.getError_no(),userT2InfoBack.getError_info(),UserLoginBack.class);
        }

        //customer数据组装
//        UserEntity bgUser = userService.getUserEntity(userEntity);
        UserBizServiceImpl userBizService = new UserBizServiceImpl();
        UserCache userCache = new UserCache();
        BrokerVO brokerVO = new BrokerVO();
        CustomerBackVo customerBackVo = new CustomerBackVo();
        customerBackVo.setCustomer_id(userEntity.getAccounts_id());
        userBizService.initParentField(customerBackVo, userEntity);
        brokerVO.setUser(customerBackVo);
        form.setUser_key(String.valueOf(userEntity.getUser_id()));
        UserTokenUtil.setBGBrokerVO(brokerVO, form);
        userCache.setBrokerVO(brokerVO);
        userCache.setAccess_token(userT2LoginBack.getUser_token());
        UserLoginBack userLoginBack = new UserLoginBack();
        String user_token = UserTokenUtil.addUserToken(userCache);
        //本地注册成功后发送数据到后台注册
        RegForm regForm = new RegForm();
        regForm.setAlias_name(alias_name);
        regForm.setMobile_tel(mobile_tel);
        regForm.setNeed_user_id("1");
        regForm.setUser_id(String.valueOf(userEntity.getUser_id()));
        regForm.setSendercomp_id(form.getSendercomp_id());
        regForm.setUser_token(user_token);
        HeaderForm headerForm = new HeaderForm();
        headerForm.setCompany_id(form.getCompany_id());
        headerForm.setSendercomp_id(form.getSendercomp_id());
        regForm.setHeaderForm(headerForm);
//        regForm.setNeed_user_id(form.getNeed_user_id());
        RegBackVo backVo = lightinvestingService.func_register_authuser(regForm);
        if (backVo.getSerial_no() == null){
            logger.error("bg Server register failed errono:" + backVo.getError_no() +
                    "errInfo:" + backVo.getError_info());
            UserTokenUtil.deleteUserToken(user_token);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            throw new RuntimeException(backVo.getError_no() + "|" + backVo.getError_info());
            return VOUtil.genBGErrorResult(backVo.getError_no(), backVo.getError_info(), UserLoginBack.class);
        }
        userLoginBack.setUser_token(user_token);
        //删除游客token
        UserTokenUtil.deleteUserToken(form.getUser_token());


        if (null != inviteUser){
            try {
                InviteLog inviteLog = new InviteLog();
                inviteLog.setInvite_code(form.getInvite_code());
                inviteLog.setInviter_id(inviteUser.getUser_id());
                inviteLog.setInvitee_id(Long.parseLong(userT2InfoBack.getUser_id()));
                inviteLog.setCompany_id(form.getCompany_id());
                inviteLog.setCreate_time(System.currentTimeMillis());
                inviteLogService.save(inviteLog);
                inviteUser.setInvite_num(inviteUser.getInvite_num()+1);
                userService.updateInviteNum(inviteUser);
                CreditsOperForm creditsOperForm = new CreditsOperForm();
                creditsOperForm.setCompany_id(company_id);
                creditsOperForm.setUser_id(Long.parseLong(userT2InfoBack.getUser_id()));
                creditsOperForm.setOpera_credits(1000);
                creditsService.functionAddCredits(creditsOperForm);

                CreditsLog creditsLog = new CreditsLog();
                creditsLog.setUser_id(Long.parseLong(userT2InfoBack.getUser_id()));
                creditsLog.setCompany_id(company_id);
                creditsLog.setOpera_credits(10000);
                creditsLog.setOpera_direction(1);
                creditsLog.setOpera_type(BusinessType.REGISTER.toInt());
                creditsLog.setMultiply(1);
                creditsLog.setMemo("被推荐奖励1000积分");
                creditsLogService.save(creditsLog);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        userLoginBack.setAlias(userEntity.getUser_id());
        return VOUtil.setSuccessResult(userLoginBack);
    }



    @Transactional
    public UserLoginBack func_capital_account_login(CapitalLoginForm param){
        param.setCompany_id(param.getTenant_id());
        param.setAlias_name("dongbei_"+System.nanoTime());
        CapitalAccountLoginForm form = JSON.parseObject(JSON.toJSONString(param),CapitalAccountLoginForm.class);
//        UserEntity isRegUser = userService.getUserEntity(new UserEntity(param.getLogin_account(), "100",
//                param.getSendercomp_id(), param.getTenant_id()));
        form.setMobile("99000000000");
        form.setUser_type("3");

        form.setRegister_flag("2");
        form.setAlias_name(param.getAlias_name());
        CapitalAccountLoginVo capitalAccountLoginVo= userCenterService.func_capital_account_login(form);
        if(!"0".equals(capitalAccountLoginVo.getError_no())){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return VOUtil.genErrorResult(capitalAccountLoginVo.getError_no(),capitalAccountLoginVo.getError_info(), UserLoginBack.class);
        }
        //通过中台来判断是否注册，没注册去后台注册
        UserLoginBack userLoginBack= new UserLoginBack();
        UserBizServiceImpl userBizService = new UserBizServiceImpl();
        String user_token="";
        UserCache userCache = new UserCache();
        UserEntity verifyUser = userService.get(capitalAccountLoginVo.getUser_id()+"");
        if(null == verifyUser){
            Customer new_customer =new Customer(param.getAlias_name(),param.getLogin_account(),
                    System.currentTimeMillis(), param.getCompany_id());
            customerService.addCustomer(new_customer);

            //刷新user信息
            long customer_id = new_customer.getCustomer_id();
            //更新user表
            String user_key = String.valueOf(System.nanoTime());
            UserEntity userEntity = new UserEntity();
            userEntity.setUser_id(capitalAccountLoginVo.getUser_id());
            userEntity.setAccounts_id(customer_id);
            userEntity.setCompany_id(param.getCompany_id());
            userEntity.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
            userEntity.setSendercomp_id(param.getSendercomp_id());
            userEntity.setUser_name(param.getLogin_account());
            userEntity.setAlias_name(param.getAlias_name());
            userEntity.setUser_status(String.valueOf(UserStatus.NORMAL.getVal()));
            userEntity.setMobile(form.getMobile());
            userEntity.setInvite_code(DecimalFormatUtil.format(capitalAccountLoginVo.getUser_id(),"00000000"));
            userService.addUser(userEntity);
            BrokerVO brokerVO = new BrokerVO();
            CustomerBackVo customerBackVo = new CustomerBackVo();
            customerBackVo.setCustomer_id(userEntity.getAccounts_id());
            userBizService.initParentField(customerBackVo, userEntity);
            brokerVO.setUser(customerBackVo);
            UserTokenUtil.setBGBrokerVO(brokerVO, param);
            userCache.setBrokerVO(brokerVO);
            userCache.setAccess_token(capitalAccountLoginVo.getUser_token());
            userCache.setIsCapitalAccount(capitalAccountLoginVo.getIsCapitalAccount());
            user_token =capitalAccountLoginVo.getUser_token();
            //本地注册成功后发送数据到后台注册
            RegForm regForm = new RegForm();
            regForm.setAlias_name(param.getLogin_account());
            regForm.setMobile_tel(param.getMobile());
            regForm.setNeed_user_id("1");
            regForm.setUser_id(String.valueOf(userEntity.getUser_id()));
            regForm.setSendercomp_id(param.getSendercomp_id());
            regForm.setUser_token(user_token);
            HeaderForm headerForm = new HeaderForm();
            headerForm.setCompany_id(param.getCompany_id());
            headerForm.setSendercomp_id(param.getSendercomp_id());
            regForm.setHeaderForm(headerForm);
            RegBackVo backVo = lightinvestingService.func_register_authuser(regForm);
            if (backVo.getSerial_no() == null){
                logger.error("bg Server register failed errono:" + backVo.getError_no() +
                        "errInfo:" + backVo.getError_info());
                UserTokenUtil.deleteUserToken(user_token);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return VOUtil.genBGErrorResult(backVo.getError_no(), backVo.getError_info(), UserLoginBack.class);
            }

        }else{
            BrokerVO brokerVO = new BrokerVO();
            UserTokenUtil.setBGBrokerVO(brokerVO, param);
            brokerVO.setCompany_id(param.getCompany_id());
            brokerVO.setSendercomp_id(param.getSendercomp_id());
            userCache.setBrokerVO(brokerVO);
            userCache.setAccess_token(capitalAccountLoginVo.getUser_token());
            Customer customer = customerService.getCustomer(new Customer(verifyUser.getAccounts_id()));
            if(customer!=null) {
                CustomerBackVo customerBackVo = JSON.parseObject(JSON.toJSONString(customer), CustomerBackVo.class);
                userBizService.initParentField(customerBackVo, verifyUser);
                customerBackVo.setAlias_name(param.getAlias_name());
                customerBackVo.setAvatar(param.getAvatar());
                customerBackVo.setCity_name(param.getCity_name());
                customerBackVo.setProvince_name(param.getProvince_name());
                userCache.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                customerBackVo.setUser_type(String.valueOf(UserType.CUSTOMER.getVal()));
                customerBackVo.setUser_key(verifyUser.getUser_key());
                userCache.getBrokerVO().setUser(customerBackVo);
            }

        }
        userCache.setIsCapitalAccount(capitalAccountLoginVo.getIsCapitalAccount());
        user_token =capitalAccountLoginVo.getUser_token();
        UserTokenUtil.updateUserToken(capitalAccountLoginVo.getUser_token(),userCache);
        userLoginBack.setUser_id(capitalAccountLoginVo.getUser_id());
        userLoginBack.setUser_token(user_token);
        return userLoginBack;
    }
}


